package mongo

import (
	"gitee.com/dreamwood/ez"
	"strings"
)

type QueryBuilder struct {
	Conditions map[string]interface{} `json:"_where"` //查询条件
	Order      []string               `json:"_order"` //排序
	Limit      int                    `json:"limit"`  //每页数量
	Page       int                    `json:"page"`   //页码从1开始
	Total      int64                  `json:"total"`  //总数
	Depth      int                    `json:"_d"`     //层深
	Group      []string               `json:"_g"`     //分组
	IsTree     bool                   `json:"_tree"`  //是否要求树形结构
	Relation   []string               `json:"_rel"`   //关联数据的获取
}

func (this *QueryBuilder) FeedBack() map[string]interface{} {
	var data = make(map[string]interface{})
	data["page"] = this.Page
	data["total"] = this.Total
	data["limit"] = this.Limit
	return data
}
func (this *QueryBuilder) GetFilter() map[string]interface{} {
	conditions := ez.M{}
	for k, item := range this.Conditions {
		if item != "" {
			if strings.HasSuffix(k, "__like") {
				k = strings.ReplaceAll(k, "__like", "__icontains")
			}
			if strings.HasSuffix(k, "__sw") {
				k = strings.ReplaceAll(k, "__sw", "__startswith")
			}
			if strings.HasSuffix(k, "__ew") {
				k = strings.ReplaceAll(k, "__ew", "__endswith")
			}
			if strings.HasSuffix(k, "__eq") {
				k = strings.ReplaceAll(k, "__eq", "__iexact")
			}
			conditions[k] = item
		}
	}
	return conditions
}

func (this *QueryBuilder) SetId(id int) *QueryBuilder {
	if this.Conditions == nil {
		this.Conditions = make(map[string]interface{})
	}
	this.Conditions["id"] = id
	return this
}
func (this *QueryBuilder) GetWhere() map[string]interface{} {
	return this.GetFilter()
}

func (this *QueryBuilder) GetNoWhere() map[string]interface{} {
	return this.GetFilter()
}

func (this *QueryBuilder) GetOrder() []string { return this.Order }

func (this *QueryBuilder) GetOrderOne() string {
	if len(this.Order) == 0 {
		return ""
	} else {
		return this.Order[0]
	}
}

func (this *QueryBuilder) GetLimit() int { return this.Limit }

func (this *QueryBuilder) GetOffset() int {
	offset := this.Page*this.Limit - this.Limit
	if offset < 0 {
		offset = 0
	}
	return offset
}

func (this *QueryBuilder) GetGroup() string {
	if len(this.Group) == 0 {
		return "default"
	}
	groupString := ""
	for _, group := range this.Group {
		groupString = groupString + " " + group
	}
	return groupString[1:]
}

func (this *QueryBuilder) GetDepth() int {
	if this.Depth == 0 {
		return 1
	}
	return this.Depth
}

func (this *QueryBuilder) Get() []interface{} {
	re := []interface{}{this.Conditions, this.Order, this.Limit, this.Page, this.Total}
	return re
}
